package com.ruoyi.eduManage.service.impl;

import com.ruoyi.eduManage.domain.EduClass;
import com.ruoyi.eduManage.domain.EduTeacher;
import com.ruoyi.eduManage.domain.dto.DailyStatisticsMailDTO;
import com.ruoyi.eduManage.service.IEduClassService;
import com.ruoyi.eduManage.service.IEduTeacherService;
import com.ruoyi.eduManage.service.IEduHomeworkSubmitService;
import com.ruoyi.eduManage.service.IMailDataService;
import com.ruoyi.eduManage.utils.MailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 邮件数据服务实现类
 * 
 * @author ruoyi
 */
@Service
public class MailDataServiceImpl implements IMailDataService {

    private static final Logger log = LoggerFactory.getLogger(MailDataServiceImpl.class);
    @Autowired
    private IEduTeacherService eduTeacherService;
    
    @Autowired
    private IEduClassService eduClassService;
    
    @Autowired
    private IEduHomeworkSubmitService eduHomeworkSubmitService;

    @Autowired
    private MailUtils mailUtils;
    
    @Override
    public List<DailyStatisticsMailDTO> getAllTeachersDailyStatistics(String startDate, String endDate, Integer expectedDays) {
        List<DailyStatisticsMailDTO> result = new ArrayList<>();
        
        // 获取所有教师
        List<EduTeacher> teachers = eduTeacherService.selectEduTeacherList(new EduTeacher());
        
        for (EduTeacher teacher : teachers) {
            DailyStatisticsMailDTO dto = getTeacherDailyStatistics(teacher.getTeacherNo(), startDate, endDate, expectedDays);
            if (dto != null) {
                result.add(dto);

                // 生成周度积分统计图片并作为附件发送邮件
                try {
                    // 收集该教师的班级ID
                    EduClass classQuery = new EduClass();
                    classQuery.setTeacherNo(teacher.getTeacherNo());
                    List<EduClass> classes = eduClassService.selectEduClassList(classQuery);
                    List<String> classIds = new ArrayList<>();
                    for (EduClass c : classes) {
                        if (c.getClassId() != null) {
                            classIds.add(String.valueOf(c.getClassId()));
                        }
                    }

                    String dateForWeek = (endDate != null && !endDate.isEmpty()) ? endDate : new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
                    byte[] png = eduHomeworkSubmitService.generateWeeklyPointsImage(dateForWeek, classIds);

                    List<MailUtils.Attachment> attachments = new ArrayList<>();
                    if (png != null && png.length > 0) {
                        String fname = "本周奖励积分统计_" + teacher.getTeacherName() + "_" + dateForWeek.replace("-", "") + ".png";
                        attachments.add(new MailUtils.Attachment(fname, "image/png", png));
                    }

                    Map<String, Object> vars = new HashMap<>();
                    vars.put("teacherName", dto.getTeacherName());
                    vars.put("startDate", dto.getStartDate());
                    vars.put("endDate", dto.getEndDate());
                    vars.put("classDataList", dto.getClassDataList());

                    String subject = "学生作业提交统计报告 - " + (dto.getEndDate() != null ? dto.getEndDate() : dateForWeek);
                    mailUtils.sendTemplateMailWithConfig(teacher.getEmail(), subject, "daily-statistics-simple", vars, true, attachments);
                } catch (Exception ignore) {
                    log.error(ignore.toString());
                    throw new RuntimeException(ignore.getMessage());
                }
            }
        }
        
        return result;
    }
    
    @Override
    public DailyStatisticsMailDTO getTeacherDailyStatistics(String teacherNo, String startDate, String endDate, Integer expectedDays) {
        try {
            // 获取教师信息
            EduTeacher teacherQuery = new EduTeacher();
            teacherQuery.setTeacherNo(teacherNo);
            List<EduTeacher> teachers = eduTeacherService.selectEduTeacherList(teacherQuery);
            if (teachers.isEmpty()) {
                return null;
            }
            EduTeacher teacher = teachers.get(0);
            
            // 跳过没有邮箱的教师
            if (teacher.getEmail() == null || teacher.getEmail().trim().isEmpty()) {
                return null;
            }
            
            // 获取教师的班级
            EduClass classQuery = new EduClass();
            classQuery.setTeacherNo(teacherNo);
            List<EduClass> classes = eduClassService.selectEduClassList(classQuery);
            
            if (classes.isEmpty()) {
                return null;
            }
            
            // 创建DTO
            DailyStatisticsMailDTO dto = new DailyStatisticsMailDTO();
            dto.setTeacherName(teacher.getTeacherName());
            dto.setTeacherEmail(teacher.getEmail());
            dto.setStartDate(startDate);
            dto.setEndDate(endDate);
            
            List<DailyStatisticsMailDTO.ClassStatisticsData> classDataList = new ArrayList<>();
            
            for (EduClass eduClass : classes) {
                // 调用Service获取每日提交详情
                Map<String, Object> detailData = eduHomeworkSubmitService.getDailySubmitDetailData(
                    startDate, endDate, eduClass.getClassCode(), expectedDays);
                
                if (detailData != null && Boolean.TRUE.equals(detailData.get("success"))) {
                    DailyStatisticsMailDTO.ClassStatisticsData classData = new DailyStatisticsMailDTO.ClassStatisticsData();
                    classData.setClassCode(eduClass.getClassCode());
                    classData.setClassName((String) detailData.get("className"));
                    classData.setDateColumns((List<String>) detailData.get("dateColumns"));
                    classData.setTotalStudents((Integer) detailData.get("totalStudents"));
                    classData.setTotalSubmissions((Integer) detailData.get("totalSubmissions"));
                    classData.setSubmittedCount((Integer) detailData.get("submittedCount"));
                    classData.setAttendanceRate((Double) detailData.get("attendanceRate"));
                    
                    // 转换学生数据
                    List<Map<String, Object>> studentDataList = (List<Map<String, Object>>) detailData.get("studentData");
                    List<DailyStatisticsMailDTO.StudentDailyData> studentDailyDataList = new ArrayList<>();
                    
                    for (Map<String, Object> studentInfo : studentDataList) {
                        DailyStatisticsMailDTO.StudentDailyData studentData = new DailyStatisticsMailDTO.StudentDailyData();
                        studentData.setStudentNo((String) studentInfo.get("studentNo"));
                        studentData.setStudentName((String) studentInfo.get("studentName"));
                        studentData.setEnglishName((String) studentInfo.get("englishName"));
                        studentData.setDailyStatus((String) studentInfo.get("dailyStatus"));
                        studentData.setTotalScore((Integer) studentInfo.get("totalScore"));
                        studentDailyDataList.add(studentData);
                    }
                    
                    classData.setStudentData(studentDailyDataList);
                    classDataList.add(classData);
                }
            }
            
            dto.setClassDataList(classDataList);
            return dto;
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}